package com.hori3d.rc;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.security.auth.callback.Callback;

import com.hori3d.rc.bean.Printer;
import com.hori3d.rc.service.ConnectPrinterService;
import com.hori3d.rc.service.PrintTask;
 
import com.hori3d.rc.service.ConnectPrinterService.LocalBinder;
import com.hori3d.rc.utils.Logger;
import com.shizhefei.view.indicator.FragmentListPageAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.ScrollIndicatorView;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorFragmentPagerAdapter;
import com.shizhefei.view.indicator.slidebar.ColorBar;
import com.shizhefei.view.indicator.transition.OnTransitionTextListener;

public class MainActivity extends BaseActivity {
	int i = 0;
	int PrintCodeline = 0;
    String  TAG="MainActivity";
	private MainActivity mContext;

	ImageView printerConnectedIV, printerDisconnectedIV, printerCommunicatingIV;
	AnimationDrawable anim;
	Handler getFilesHandler;

	boolean isReadingFiles = false;
	ArrayList<String> files = new ArrayList<String>();

	boolean isContected = false;
	boolean gotFirstResponse = false;
	boolean iscommucating = false;
	boolean isRestarting = false;
	boolean isWarming = false;
	ProgressDialog pd1;
	AlertDialog.Builder builder;
	public static AlertDialog heatingAlertDialog,webprintAlertDialog;
	public static int MSG_PRINTER_RESPENSE = 100;
	TimerTask checkFileToPrintTimer;

	Boolean bound = false;
	ConnectPrinterService conPrinterService;

	Timer timer = new Timer(); // 定时器 用于执行各种定时查询
	Timer warmingTimer = new Timer();
	Handler refreshHandler=new Handler();
	boolean hasInit=false;  
	
	private IndicatorViewPager indicatorViewPager;
	private LayoutInflater inflate;
	private String[] names = { "状态", "移轴", "速度", "换料", "打印", "设置", "关于" };
	private ScrollIndicatorView indicator;
	private int tabSize = names.length;

	private ServiceConnection connection = new ServiceConnection() {
		@Override
		public void onServiceDisconnected(ComponentName name) {
			bound = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			LocalBinder binder = (LocalBinder) service;
			conPrinterService = binder.getService();
			bound = true;
			 
			while(!hasInit&&m3Dprinter.getPrinterStatusCode()!=Printer.PRINTER_STATUS_WAITING)
				{
					Log.i("leo", "等待连接串口");  			
				}
					Log.e(TAG,"初始化设置");
				//设定网络打印文件监听器
					hasInit=true;
					timer.schedule(new TimerTask() {
					
						@Override
						public void run() {
						
						}
					}, 0, 1000);
					
		}
	};
 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		m3Dprinter = app.getPrinter();
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
				.detectNetwork().penaltyLog().build());
		// 设置横屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); // 横屏
	
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// hide statusbar of Android
		// could also be done later
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// setContentView(R.layout.activity_main);

		setContentView(R.layout.activity_main);

		// ToggleButton toggleButton = (ToggleButton)
		// findViewById(R.id.toggleButton1);
		ViewPager viewPager = (ViewPager) findViewById(R.id.moretab_viewPager);
		indicator = (ScrollIndicatorView) findViewById(R.id.moretab_indicator);
		indicator.setScrollBar(new ColorBar(this, getResources().getColor(R.color.light_blue), 5));

		// 设置滚动监听
		int selectColorId = R.color.tab_top_text_2;
		int unSelectColorId = R.color.tab_top_text_1;
		indicator.setOnTransitionListener(
				new OnTransitionTextListener().setColorId(this, selectColorId, unSelectColorId));

		viewPager.setOffscreenPageLimit(2);
		indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
		inflate = LayoutInflater.from(getApplicationContext());
		indicatorViewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));

		createWarmingDialog(); // 创建加温提示 对话框

		//页面刷新线程
		 Thread refreshThread=new Thread(new  Runnable() {
				Long lastmodtime = (long) 0;
		   	int lastPrinterState=m3Dprinter.getPrinterStatusCode();
			 public void run() {
				 while(true)
			 {
              /**
               * 刷新加温对话框	 
               */
				 //如果打印机状态为加温 则显示加温对话框
				if(lastPrinterState==Printer.PRINTER_STATUS_HEATING) 
			       refreshHandler.sendEmptyMessage(OPEN_HEATING_ALERT_DIALOG);
				else //否则，关掉加温对话框
					  refreshHandler.sendEmptyMessage(CLOSE_HEATING_ALERT_DIALOG);

			  /**
			   * 刷新web接受文件对话框
			   */
				//Log.e("leo", "查");
				File dir = new File(m3Dprinter.webPrintFilePath);

				File[] fs = dir.listFiles();
				if (lastmodtime != dir.lastModified()) {
				//	Log.e("leo", "进行搜查");
					lastmodtime = dir.lastModified();
					for (int i = 0; i < fs.length; i++) {
						if (fs[i].getName().contains("toprint")) {
							Logger.e("发现待打印文件" + fs[i].getName());
							 buzz(50, 6);
							renameFile(fs[i].getAbsolutePath());
							m3Dprinter.webPrintFileRecv=fs[i].getAbsolutePath().substring(0, fs[i].getAbsolutePath().indexOf("gcode")+5);
							Logger.e(m3Dprinter.webPrintFileRecv);
							 refreshHandler.sendEmptyMessage(WEB_FILE_RECV_ALERT_DIALOG);
						}
					}
				}
				
				if(m3Dprinter.webPrintFileRecv!="")

				lastPrinterState=m3Dprinter.getPrinterStatusCode();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			 }
			}
		});
		 refreshThread.start();
		
		 refreshHandler=new Handler(){
			 @Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				 switch (msg.what) {
				case OPEN_HEATING_ALERT_DIALOG:
					if(heatingAlertDialog==null)
						createWarmingDialog();
						heatingAlertDialog.show();
					break;
					
				case CLOSE_HEATING_ALERT_DIALOG:
				if(heatingAlertDialog!=null)
					heatingAlertDialog.dismiss();
					break;
					
				case WEB_FILE_RECV_ALERT_DIALOG:
					showWebPrintDialog();
					break;
				default:
					break;
				}	 
			}
		 };
		 
		 
		 
		 Logger.e(App.ctx.getExternalFilesDir(null).getAbsolutePath());
	//end oncreate()	 
	}

	public  static final int  OPEN_HEATING_ALERT_DIALOG=1;
	public  static final int   CLOSE_HEATING_ALERT_DIALOG=12;
	public  static final int   WEB_FILE_RECV_ALERT_DIALOG=2;
	
	 public void renameFile(String file) {
			
		 File toBeRenamed = new File(file);
		 String toFileName = toBeRenamed.getAbsolutePath()
				 .replaceAll("gcodetoprint","gcode");

		 //检查要重命名的文件是否存在，是否是文件
		 if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {
		
		 System.out.println("File does not exist: " + file);
		 	return;
		 }
    
		 File newFile = new File(toFileName);
     
		 //修改文件名
		 if (toBeRenamed.renameTo(newFile)) {
		 System.out.println("File has been renamed.");
		 } else {
		 System.out.println("Error renmaing file");
		 }
	 }
		

	private class MyAdapter extends IndicatorFragmentPagerAdapter {

		public MyAdapter(FragmentManager fragmentManager) {
			super(fragmentManager);
		}

		@Override
		public int getCount() {
			return tabSize;
		}

		@Override
		public View getViewForTab(int position, View convertView, ViewGroup container) {
			if (convertView == null) {
				convertView = inflate.inflate(R.layout.tab_top, container, false);
			}
			TextView textView = (TextView) convertView;
			textView.setText(names[position % names.length]);
			textView.setPadding(20, 0, 20, 0);
			return convertView;
		}

		@Override
		public Fragment getFragmentForPage(int position) {
			switch (position + 1) {
			case 1:
				return new StastusFragment();

			case 2:
				return new MoveFragment();

			case 3:
				return new SpeedFragment();

			case 4:
				return new ChangeMaterialFragment();

			case 5:
				return new FileFragment();

			case 6:
				return new OptionFragment();

			case 7:
				return new AboutFragment();

			default:
				break;
			}
			return null;

		}

		@Override
		public int getItemPosition(Object object) {
			return FragmentListPageAdapter.POSITION_NONE;
		}

	};

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		/**
		 * 绑定“连接打印机模块”服务
		 */
		Log.i("leo", "onStart");
		Intent intent = new Intent(this, ConnectPrinterService.class);
		bindService(intent, connection, Context.BIND_AUTO_CREATE);
       

	}

	/**
	 * 创建加温提示 dialog 
	 */
	private void createWarmingDialog() {
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setMessage("开始打印"+m3Dprinter.getPrintingFile()+"。打印机升温到到目标温度后,开始打印。");
		builder.setTitle("提示");
		builder.setCancelable(false);
		heatingAlertDialog = builder.create();
	}
	
	
	/**
	 * 创建收到文件 提示对话框
	 */
	private void showWebPrintDialog() {
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setTitle("无线打印");
		//如果正在打印，只提示收到文件
		if(m3Dprinter.isPrintingOrPausing())
				builder.setMessage("收到文件"+m3Dprinter.webPrintFileRecv);
		else
			{ 
				builder.setMessage("收到文件"+m3Dprinter.webPrintFileRecv.substring(m3Dprinter.webPrintFileRecv.lastIndexOf("\\"))+",是否要打印？");
				builder.setPositiveButton("确定", new OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						
						m3Dprinter.prtTask=new PrintTask(new File(m3Dprinter.webPrintFileRecv),conPrinterService);
						m3Dprinter.webPrintFileRecv="";
					}
				});
			}	
		builder.setNegativeButton("取消", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					m3Dprinter.webPrintFileRecv="";		
				}
			});
		webprintAlertDialog = builder.create();
		webprintAlertDialog.show();
		}
	
	
	
 

	// 打印状态判断 暂时省略
	// else if (respString.contains("ok Print:"))
	// ok Print:-1|-1|-1

	// String subString = respString.substring(9);
	// String[] truePrintData = subString.split("\\|");
	// m3Dprinter.setPrinterStatusCode(Integer.valueOf(truePrintData[0]));
	// m3Dprinter.setPrintingTime(Integer.valueOf(truePrintData[1]));
	// m3Dprinter.setPrintingProcess(Integer.valueOf(truePrintData[2]));
	// m3Dprinter.setPrintingFile(truePrintData[3]);
	//
	// if (truePrintData[4].equals("1"))
	// m3Dprinter.setAutoPowerOff(true);
	// else
	// m3Dprinter.setAutoPowerOff(false);

	public void sendCmd(String cmd) {
		conPrinterService.sendCMD(cmd);
	}

	// 当加温状态时 拦截按键事件事件
	// @@@@之后需要实现 加温后
	public boolean dispatchKeyEvent(android.view.KeyEvent event) {
		if ((m3Dprinter.getPrinterStatusCode() == Printer.PRINTER_STATUS_HEATING)
				&& (event.getKeyCode() == KeyEvent.KEYCODE_BACK))
			return true;
		else
			return super.dispatchKeyEvent(event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// conPrinterService.closeSocket();
		Log.e("leo", "这里这里");
		unbindService(connection);

	}

	protected void buzz(int p, int times) {
		while (times-- > 0) {
			sendCmd(Printer.CMD_BEEZER + p);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	private void toTab(int id)
	{
		indicatorViewPager.setCurrentItem(id, true);
	}

}
